package com.sailor.excel.easyExcel;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
public class EasyExcelHelp {
    private EasyExcelHelp() {
    }

    /**
     * 通用excel导出
     *
     * @param response HttpServletResponse
     * @param fileName 文件名称
     * @param data     数据列表
     * @param clz      导出模板类
     * @param <T>
     */
    public static <T> void commonExport(HttpServletResponse response, String fileName, List<T> data, Class<T> clz) throws Exception {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileNameEncode = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileNameEncode + ".xlsx");
            EasyExcel.write(response.getOutputStream(), clz)
                    .sheet("Sheet1")
                    .registerWriteHandler(new CustomCellWriteHandler())
                    .doWrite(data);
        } catch (Exception e) {
            log.error("export eror, fileName:{}", e, fileName);
            throw new Exception("文件下载异常，请稍后再试");
        }
    }
}
